<?php
/**
 * WithdrawController.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-06-01 21:17:04
 * @modified   2023-06-01 21:17:04
 */

namespace Beike\Seller\Http\Controllers;

use Beike\Seller\Repositories\WithdrawRepo;
use Beike\Seller\Services\WithdrawService;
use Illuminate\Http\Request;

class WithdrawController extends Controller
{
    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function index()
    {
        $sellerId   = current_seller_user()->seller_id;
        $data       = [
            'withdraws' => WithdrawRepo::list($sellerId),
        ];

        return view('seller::pages.withdraws.index', $data);
    }

    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function create()
    {
        $seller = current_seller_user()->seller;
        if (! $seller->bank_account || ! $seller->bank_name || ! $seller->bank) {
            return redirect(seller_route('withdraws.index'))->withErrors(['error' => trans('seller::withdraw.bank_account_missing', ['edit_link' => seller_route('edit.index')])]);
        }

        $data = [
            '_redirect'    => $this->getRedirect(),
        ];

        return view('seller::pages.withdraws.form', $data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(Request $request)
    {
        try {
            WithdrawService::create($request->get('amount'));
        } catch (\Exception $e) {
            return redirect(seller_route('withdraws.create'))->withInput()->withErrors(['error' => $e->getMessage()]);
        }

        return redirect(seller_route('withdraws.index'))->with('success', trans('common.created_success'));
    }
}
